import random

from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django_redis import get_redis_connection

from app01.utils.script import uni_sms
from app01.utils.encrypt.md5 import md5
from app01 import models

class LoginForms(forms.Form):
    role = forms.ChoiceField(label="角色",choices=(("1","管理员"),("2","客户")),widget=forms.Select(attrs={"class": "form-control"}))
    name = forms.CharField(label="用户名",widget=forms.TextInput(attrs={"class": "form-control", "placeholder":"请输入用户名"}))
    password = forms.CharField(label="密码",widget=forms.PasswordInput(attrs={"class": "form-control", "placeholder": "请输入密码"}))
    def clean_name(self):
        user = self.cleaned_data.get("name")
        print("长度",len(user))
        if len(user) < 5:
            raise ValidationError("用户名过短")
        return user
    def clean_password(self):
        return md5(self.cleaned_data.get("password"))
    # def clean(self):
    #     user = self.cleaned_data.get("name")
    #     if user == "jk123":
    #         raise ValidationError("错了")


class SmsForms(forms.Form):
    role = forms.ChoiceField(label="角色", choices=(("1", "管理员"), ("2", "客户")),widget=forms.Select(attrs={"class": "form-control", "name": "role"}))
    mobile = forms.CharField(label="手机号",required=True, widget=forms.TextInput(attrs={"class": "form-control", "name": "mobile"}))
    code = forms.CharField(label="短信验证码", validators=[RegexValidator(r'^[0-9]+$'), "验证码必须为数字"], widget=forms.TextInput(attrs={"class": "form-control", "name": "code"}))

class MobileForms(forms.Form):
    role = forms.ChoiceField(label="角色", choices=(("1", "管理员"), ("2", "客户")),
                             widget=forms.Select(attrs={"class": "form-control", "name": "role"}))
    mobile = forms.CharField(label="手机号", required=True,validators=[RegexValidator(r'^1[385]\d{9}$', "手机号码格式错误")])
    def clean_mobile(self):
        mobile = self.cleaned_data.get("mobile")
        role = self.cleaned_data.get("role")
        sms_code = str(random.randint(1000, 9999))
        if role == "1":
            exists = models.Administrator.objects.filter(mobile=mobile).first()
        else:
            exists = models.Customer.objects.filter(mobile=mobile).first()
        if not exists:
            raise ValidationError("手机号不存在")
        is_success = uni_sms.send_code(mobile, sms_code)
        if not is_success:
            raise ValidationError("验证码发送失败")
        conn = get_redis_connection("default")
        conn.set(mobile, sms_code, ex=60)
        return mobile


class SmsLoginForms(forms.Form):
    role = forms.ChoiceField(label="角色", choices=(("1", "管理员"), ("2", "客户")),widget=forms.Select(attrs={"class": "form-control", "name": "role"}))
    mobile = forms.CharField(
        label="手机号",
        required=True,
        validators=[RegexValidator(r'^1[385]\d{9}$', "手机号码格式错误")])
    code = forms.CharField(
        label="短信验证码",
        validators=[RegexValidator(r'^[0-9]{4}$', "验证码格式错误")])

    def clean_code(self):
        mobile = self.cleaned_data.get('mobile')
        code = self.cleaned_data['code']
        if not mobile:
            return code
        conn = get_redis_connection("default")
        cache_code = conn.get(mobile)
        if not cache_code:
            raise ValidationError("验证码过期或者未发送验证码")
        if code != cache_code.decode("utf-8"):
            raise ValidationError("验证码过期或者未发送验证码")
        return code










class AddLevelForms(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control","id":"level","name":"level"}))
    present = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control","id":"discount","name":"discount"}))
